import { createApp } from "vue";
import axios from "axios"; // 1、引入

import {getToken} from '@/utils/auth'
import { ElMessage } from 'element-plus'

export const productUrl='http://localhost:3000';
let has306err = false
// 创建axios实例
const service = axios.create({
	baseURL: process.env.NODE_ENV=="development"?'/api':productUrl, // api 的 base_url
	timeout: 10000 // 请求超时时间
})
service.interceptors.request.use(
  config => {
    var token =getToken();
    if (token) {
      /* switch (config.method) {
      case 'get':
        if (!config.params) {
          config.params = {}
        }
        config.params.token = token
        break
      case 'post':
        // config.data.token = token;
        break
      default:
        break
    } */
      config.headers["token"] = token;
    }
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  },
);

service.interceptors.response.use(
	response => {
		// console.log('response: ', response);
		let res = response.data
		// console.log('res: ', res);
		if (typeof res !== 'object') {
			ElMessage.error('服务端异常！')
			return Promise.reject(res)
		}
		var type = ''
		if (res.code != '001') {
			type = 'error';
			if (type === "error"&&res.msg&&res.msg!="登录失败！") {
				ElMessage({
					message: res.msg,
					type,
					duration: 3.5 * 1000,
					dangerouslyUseHTMLString: true
				})
			}
			/* if (res.code == 419) {
				removeToken();
				router.push('/login')
			} */
			return Promise.reject(res)
		}
		return res
	},
	error => {
		// console.log('error: ', error);
		if(error.response){
			switch (error.response.status) {
				case 500:
					ElMessage({
						message: "网络连接异常，请重试。",
						type: "warning",
						duration: 3 * 1000,
						dangerouslyUseHTMLString: true
					})
					break;
				default:
					break
			}
		}

		return Promise.reject(error)
	}
);

export default service